<template>
  <div class="app-container">

    <!-- 添加或修改绩效基本信息对话框 -->
    <projectView :datas="form" :key="form.projectNo" :column="3" :sizes="'large'"></projectView>


    <!-- 是否有 超级管理员 项目经理 销售 销售负责人 商务 财务权限之一  -->
    <div>
      <el-divider style="font-size: 16px; font-weight: bold;">项目质保信息</el-divider>
      <el-button v-if="form.saleCom == '1'" type="primary" plain :icon="Plus" @click="addWarrantys()"
        style="margin-bottom: 10px;">添加质保信息</el-button>
      <el-table v-loading="loading" border :data="warrantyList" @selection-change="handleSelectionChange">
        <el-table-column label="付款单位" min-width="100" align="center" prop="company" />
        <el-table-column label="结算金额" align="center" min-width="100" prop="settlementAmount" />
        <el-table-column label="质保金" align="center" min-width="100" prop="warranty" />
        <el-table-column label="质保金税率(%)" align="center" min-width="100" prop="rate">
          <template #default="scope">
            <dict-tag :options="warranty_rate" :value="scope.row.rate" />
          </template>
        </el-table-column>
        <el-table-column label="周期(月)" min-width="100" align="center" prop="cycle" />
        <el-table-column label="起始日期" min-width="100" align="center" prop="startDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="截止日期" min-width="100" align="center" prop="endDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="质保到期剩余(天)" min-width="100" align="center" prop="warrantyRemaining" />
        <el-table-column label="质保金实收金额" min-width="100" align="center" prop="receivedAmount" />
        <el-table-column label="备注" min-width="100" align="center" prop="remark" />
        <!-- <el-table-column label="操作人" min-width="100" align="center" prop="operator">
                <template #default="scope">
                  {{ cwName }}
                </template>
              </el-table-column> -->
        <el-table-column label="操作人" min-width="100" align="center" prop="operator" />
        <el-table-column label="附件" min-width="100" align="center" show-overflow-tooltip width="200" prop="fileName">
          <template #default="scope">
            <div v-if="scope.row.files">
              <el-link v-for="(file, index) in scope.row.fileName.split(',')" :key="index" type="primary"
                @click="downloadFile(scope.row, index, file)" style="display: block; margin-bottom: 5px;">
                {{ file }}
              </el-link>
            </div>
            <div v-else>
              <!-- 无文件 -->
            </div>
          </template>
        </el-table-column>

        <el-table-column v-if="form.saleCom == '1'" label="操作" align="center" fixed="right"
          :width="userStore.isMobile ? 120 : 220" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" :icon="userStore.isMobile ? '' : 'View'"
              @click="handleUpdateWarranty(scope.row, false)">修改</el-button>
            <el-button link type="primary" :icon="userStore.isMobile ? '' : 'Delete'"
              @click="handleDeleteWarranty(scope.row)">删除</el-button>
            <el-button link type="primary" :icon="userStore.isMobile ? '' : 'View'"
              @click="handleUpdateWarranty(scope.row, true)">添加实收金额</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- <template #footer>
      <div class="dialog-footer">
        <el-popconfirm v-if="(status == 1 && haveNext) || isAdmin" confirm-button-text="确认" cancel-button-text="取消"
          title="确认提交到归档环节?" @confirm="nextPhase">
          <template #reference>
            <el-button type="primary">下一步</el-button>
          </template>
        </el-popconfirm>
        <el-button v-if="(status == 1 && haveNext) || isAdmin" type="primary" @click="rollBack">回退环节</el-button>
        <el-button type="primary" @click="cancel">关 闭</el-button>
      </div>
    </template> -->

    <el-dialog title="质保信息" v-model="openWarranty" :width="userStore.isMobile ? '95%' : '700px'" append-to-body>
      <el-form ref="warrantyRef" size="large" :model="warrantyForm" :rules="warrantyRules" label-width="160px">
        <el-form-item label="付款单位" prop="company">
          <el-input v-model="warrantyForm.company" placeholder="请输入付款单位" />
        </el-form-item>
        <el-form-item label="结算金额" prop="settlementAmount">
          <el-input :disabled="true" v-model="warrantyForm.settlementAmount" placeholder="请输入结算金额" />
        </el-form-item>
        <!-- <el-form-item label="质保金比例(%)" prop="warrantyPercentage">
          <el-input type="number" @wheel.native.prevent @blur="handleBlur" v-model="warrantyForm.warrantyPercentage" placeholder="请输入质保金比例" />
        </el-form-item> -->
        <el-form-item label="质保金" prop="warranty">
          <el-input type="number" @wheel.native.prevent :disabled="true" v-model="warrantyForm.warranty"
            placeholder="" />
        </el-form-item>
        <el-form-item label="质保金税率(%)" prop="rate">
          <el-select v-model="warrantyForm.rate" placeholder="请选择税率">
            <el-option v-for="dict in warranty_rate" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="周期(月)" prop="cycle">
          <el-input v-model="warrantyForm.cycle" placeholder="请输入周期(月)" />
        </el-form-item>
        <el-form-item label="质保开始日期" prop="startDate">
          <el-date-picker clearable v-model="warrantyForm.startDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择起始日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item v-if="addMoney">
          <el-tag v-if="!userStore.isMobile" size="small">提示：质保实收金额涉及绩效分配,请如实填写</el-tag>
        </el-form-item>
        <el-form-item v-if="addMoney" label="质保金实收金额" prop="receivedAmount">
          <el-input type="number" @wheel.native.prevent v-model="warrantyForm.receivedAmount"
            placeholder="请输入质保金实收金额" />
        </el-form-item>

        <el-form-item label="质保金发票或收据" prop="files">
          <file-upload v-model="warrantyForm.files" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="warrantyForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitWarrantyForm">确 定</el-button>
          <el-button @click="cancelWarranty">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Project">
import {
  listProject, saleDetails,
  getProject, saveUserTableConfig, getUserTableConfig,
  listParticipan, getPermission,
  getStatus, listImplement
} from "@/api/project/project";
import { listAttachment, rollBackPhase } from "@/api/project/project";
import {
  listPay, listWarranty, getWarranty, delWarranty, addWarranty, updateWarranty, getWarrantyMoney, addPhase, updatePhase, listAccounting,
} from "@/api/project/project";
import {
  Plus
} from '@element-plus/icons-vue'
import { getInfo } from "@/api/login";
import { listAllUser, getUser, getPosts } from "@/api/system/user";

import { getCheck, getNextPermission, getDictionary, } from "@/api/project/dictionary";
const haveNext = ref(false)

import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();


const addPersonPer = ref(false)
const addFilePer = ref(false)
const addPayPer = ref(false)
const addImplementPer = ref(false)
const addWarrantyPer = ref(false)
const addAccountingPer = ref(false)
const loadingQuery = ref(false)
const cw = ref(false)
const allPer = ref(false)

const addMoney = ref(false)

const { proxy } = getCurrentInstance();
const { warranty_rate } = proxy.useDict('warranty_rate');
const attachmentList = ref([]);
const payList = ref([]);
const posts = ref([])
const userList = ref([])
const projectList = ref([]);
const personList = ref([]);
const accountingList = ref([]);
const implementList = ref([]);
const warrantyList = ref([]);
const open = ref(false);
const openView = ref(false);
const isView = ref(false);
const openWarranty = ref(false);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const contractAmount = ref(0)
const settlementAmount = ref(0)
const companyId = ref('')
const company = ref('')
const finance = ref(false);//当期人员是否是财务
const isAdmin = ref(false);//是否是超级管理员
const havePay = ref(false);//是否有添加付款信息的权限
const status = ref("0");
const currenrPhaseId = ref()
const formDisabled = ref(true);
let currentPhase = reactive({
  phaseCode: '',
});
const warrantyMoney = ref(0)
const receivedWarranty = ref(0)


const props = defineProps({
  datas: {
    type: Object, // 指定类型为对象
    required: false, // 是否必填
  },
  column: {
    type: Number, // 指定类型为数字
    default: 3, // 设置默认值为 3
  },
  sizes: {
    default: 'default',
  },
  projectNo: {
    default: '0',
  },


});


const { projectNo } = toRefs(props);
import projectView from "../saleProjectView.vue";

import { ref } from "vue";
import { fa, pa } from "element-plus/es/locale/index.mjs";
import { getToken } from "@/utils/auth";

const data = reactive({
  currentProject: {},
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
    saleCom: '1'
  },
  currentConfig: {

  },
  personForm: {
  },
  fileForm: {

  },
  warrantyForm: {

  },

  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    approvalDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
    projectType: [{ required: true, message: "项目类型 不能为空", trigger: "blur" }],
  },

  warrantyRules: {
    company: [{ required: true, message: "付款单位不能为空", trigger: "blur" }],
    receivedAmount: [{ required: true, message: "请填写质保金实收金额", trigger: "blur" }],
  }

});


function handleBlur() {
  const percentage = parseFloat(warrantyForm.value.warrantyPercentage);
  console.log(`质保金比例: ${percentage}%`);
  // 计算金额并保留两位小数
  warrantyForm.value.warranty = parseFloat((percentage / 100 * warrantyForm.value.settlementAmount).toFixed(2));
  console.log(`计算后的金额为: ${warrantyForm.amount}`);
}

// import {getPermission} from "@/api/project/project";
async function downloadFile(row) {
  //只有项目经理 销售负责人 吴总 能够下载正式清单 竣工结算清单 正式合同
  if (row.attachmentType == '4' || row.attachmentType == '5' || row.attachmentType == '22') {
    let params = {
      projectNo: row.projectNo,
      postIds: [2, 5, 6, 7]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
    }
    const res = await getPermission(params).then((response) => {
      console.log("下载附件", response.data);
      return response.data
    });
    if (!res) {
      proxy.$modal.msgError("暂无权限下载此附件");
      return
    }
  }

  var name = row.fileName;
  var url = row.filePath || row.files;
  // var suffix = url.substring(url.lastIndexOf("."), url.length);
  const a = document.createElement('a')
  a.setAttribute('download', name)
  a.setAttribute('target', '_blank')
  a.setAttribute('href', import.meta.env.VITE_APP_BASE_API + url)
  a.click()
}


/** 修改付款信息按钮操作 */
function handleUpdateWarranty(row, addInfo) {
  addMoney.value = addInfo
  resetWarranty();
  const _Id = row.id || ids.value
  getWarranty(_Id).then(response => {
    warrantyForm.value = response.data;
    openWarranty.value = true;

    warrantyForm.value.warranty = warrantyMoney.value

    //为空的时候使用上传竣工附件的时候的日期
    if (warrantyForm.value.startDate == null || warrantyForm.value.startDate == undefined) {
      warrantyForm.value.startDate = completeDate.value
    }


  });
}

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}


//计算方法
const calculateTheoreticalDays = (startDate, cycle) => {
  const start = new Date(startDate);
  const end = new Date(start);
  end.setMonth(start.getMonth() + parseInt(cycle));
  return Math.floor((end - start) / (86400 * 1000));
};

const calculateRemainingDays = (startDate, cycle) => {
  const start = new Date(startDate);
  const end = new Date(start);
  end.setMonth(start.getMonth() + parseInt(cycle));

  const now = new Date();
  const remaining = Math.floor((end - now) / (86400 * 1000));
  return remaining > 0 ? remaining : 0;
};
import { ElMessage } from 'element-plus';

/** 提交按钮 */
function submitWarrantyForm() {
  proxy.$refs["warrantyRef"].validate(valid => {
    if (valid) {
      warrantyForm.value.projectNo = projectNo.value
      warrantyForm.value.phaseId = 6


      if (warrantyForm.value.cycle && warrantyForm.value.startDate) {
        const theoreticalDays = calculateTheoreticalDays(
          warrantyForm.value.startDate,
          warrantyForm.value.cycle
        );

        const remainingDays = calculateRemainingDays(
          warrantyForm.value.startDate,
          warrantyForm.value.cycle
        );

        console.log(`理论天数: ${theoreticalDays}天，剩余天数: ${remainingDays}天`);

        if (remainingDays > theoreticalDays) {
          ElMessage.warning({
            message: `检测到质保起始日期可能有异常：剩余天数(${remainingDays}天)大于理论周期天数(${theoreticalDays}天)`,
            duration: 6000
          });
          return
        }
      }

      if (warrantyForm.value.id != null) {
        updateWarranty(warrantyForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openWarranty.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addWarranty(warrantyForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openWarranty.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}

/** 删除付款信息按钮操作 */
function handleDeleteWarranty(row) {
  const _Id = row.id
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delWarranty(_Id);
  }).then(() => {
    getListParticipan(projectNo.value)
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}




//添加付款信息 销售负责人添加付款信息？
function addWarrantys() {


  console.log("warrantyForm", settlementAmount);

  if (warrantyList.value.length > 0) {
    proxy.$modal.msgError("只能添加一条质保信息");
    return
  }

  //重置表单
  resetWarranty()

  warrantyForm.value.settlementAmount = settlementAmount.value
  warrantyForm.value.company = company.value
  warrantyForm.value.companyId = companyId.value
  openWarranty.value = true

  warrantyForm.value.warranty = warrantyMoney.value



}


const { form, warrantyRules, warrantyForm, currentConfig } = toRefs(data);


function getCurrUser(id) {
  getPosts(id).then(response => {
    console.log("66666666", response);
  });
}

//判断是否是销售负责人 项目经理 销售 财务 商务

async function isSale() {
  let params = {
    projectNo: projectNo.value,
    postIds: [2, 5, 6, 7]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  havePay.value = await hasPermisson(params)
  console.log("添加付款信息", havePay.value);

}

//是否是财务
async function isFinance() {
  let params = {
    projectNo: projectNo.value,
    postIds: [2, 6]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  finance.value = await hasPermisson(params)

  console.log("添加财务信息", finance.value);
}

async function hasPermisson(params) {
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  return res
}



function initData() {
  getUser().then(response => {
    posts.value = response.posts;
    console.log("岗位信息", response);
  });
  listAllUser().then(res => {
    console.log("userlist", res);
    userList.value = res
  });

  getInfo().then((res) => {
    console.log("当前用户", res);
    getCurrUser(res.user.userId)
  })
    .catch((error) => {
      console.log("error", error);
    });
}



// 取消按钮
function cancel() {
  open.value = false;
  openView.value = false
  reset();
}

// 取消按钮
function cancelWarranty() {
  openWarranty.value = false;
  resetWarranty();
}


//获取用户详细信息
function getUserInfo() {
  getInfo().then((res) => {
    const user = res.user;
    form.value.createUserName = user.nickName;
    form.value.createUserId = user.userId;
    form.value.createDeptName = user.dept.deptName
    form.value.createDept = user.deptId
    console.log("user", form);
  })
    .catch((error) => {
      console.log("error", error);
    });
}
// 表单重置
function reset() {
  form.value = {
    projectNo: null,
    projectName: null,
    createDeptName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerAddress: null,
    customerName: null,
    housekeeperProject: null,
    phaseCode: null,
    remark: null,
    minProjectAmount: null,
    maxProjectAmount: null,
    companyName: null,
    companyType: null,
    companyNo: null,
    completeDate: null
  };
  proxy.resetForm("projectRef");
}



// 表单重置
function resetWarranty() {
  warrantyForm.value = {
  };
  proxy.resetForm("warrantyRef");

}


const completeDate = ref()

/** 添加立项前期信息 */
async function handleUpdate(row) {
  activeName.value = "first"
  reset();
  isView.value = false
  const _projectNo = row.projectNo || ids.value;
  projectNo.value = row.projectNo //存放项目id
  contractAmount.value = row.contractAmount
  settlementAmount.value = row.settlementAmount
  company.value = row.customerName

  let paramsW = {
    projectNo: row.projectNo
  }

  await getWarrantyMoney(paramsW).then((response) => {
    console.log("质保金", response);
    warrantyMoney.value = response.data?.totalWarranty
    receivedWarranty.value = response.data?.receivedWarranty
  });

  getProject(_projectNo).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目基本信息";

    completeDate.value = response.data.completeDate
  });
  getListParticipan(row.projectNo)
  getNextPer(row.projectNo);

}

const activeName = ref('first')
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName
}

const cwName = ref()

async function getListParticipan(projectNo) {
  console.log("projectNoprojectNo", projectNo);

  let params = {
    projectNo: projectNo
  }

  //参与人
  listParticipan(params).then((response) => {
    console.log("参与人员", response);
    personList.value = response.data

    // 或转换为数字
    let obj = response.data.filter(item => Number(item.postId) === 6)
    cwName.value = obj[0]?.participanName || ''
    console.log("objjjj", obj);

  });

  //质保信息
  listWarranty(params).then((response) => {
    warrantyList.value = response.data;
    loading.value = false
  });


  // isFinance()
  // isSale()

  // getCurrPhase(projectNo)

}


import { reCreateWarranty } from "@/api/project/allocation";


async function nextPhase() {
  //新版点击下一步 1.下一步按钮只开给需要审核的人 隐藏与显示 获取当前配置的环节规则 请求接口校验

  if (warrantyList.value?.length > 0) {

    //有实收金额就可以提交到归档环节
    // if (warrantyList.value[0].warrantyRemaining > 0) {
    //   proxy.$modal.msgError("距离质保截至日期还剩" + warrantyList.value[0].warrantyRemaining + "天,不能提交到归档环节。",);
    //   return
    // }

    if (warrantyList.value[0].receivedAmount === undefined || warrantyList.value[0].receivedAmount === null) {
      proxy.$modal.msgError("请先添加质保实收金额");
      return
    }
    if (warrantyList.value[0].warranty != warrantyList.value[0].receivedAmount) {
      await proxy.$modal.confirm('质保金为' + warrantyList.value[0].warranty + ',质保实收金额为:' + warrantyList.value[0].receivedAmount + '，确认提交至归档环节?')
        .then(() => {
          // 用户点击了确定，继续执行后续操作
          console.log("用户确认提交");
          // 这里可以放你要执行的代码
        })
        .catch(() => {
          // 用户点击了取消，直接返回
          console.log("用户取消提交");
          return;
        });
    }

  }

  let params = {
    projectNo: projectNo.value,
    id: 6//项目质保
  }
  //校验该环节的所有配置
  const result = await getCheck(params).then(response => {//立项阶段 id写死
    console.log("项目实施校验", response);
    return response
  });
  if (result.data.permission == false) {
    proxy.$modal.msgError(result.data.message);
    return
  }
  //校验通过 更新当前阶段信息

  //如果有质保金  去做质保金部分的绩效分配
  let paramsWa = {
    projectNo: projectNo.value,
    current: 2
  }
  reCreateWarranty(paramsWa).then((response) => {
    console.log("质保金部分", response);
  });


  let updateParams = {
    id: currenrPhaseId.value,
  }
  const updateResult = await updatePhase(updateParams).then((response) => {
    console.log("更新阶段", response);
    return response
  });

  if (updateResult.data.status == 2) {//如果该环节已完成 插入下一个环节
    let addParams = {
      projectNo: projectNo.value,
      phaseId: 7,//项目验收
    }
    await addPhase(addParams).then((response) => {

    })
  }

  proxy.$modal.msgSuccess("提交成功");
  status.value = 2
  open.value = false


  let currPhase = {
    projectNo: projectNo.value,
    phaseId: 6
  }
  await getStatus(currPhase).then((response) => {
    if (response.data?.status && response.data?.status == '2') {//如果该环节已完成 跳转到下一个环节
      //判断收款是否已经收齐 收齐了跳已归档 没收齐跳待归档
      // router.push({
      //   path: '/complete/projectWait',
      //   query: { projectNo: projectNo.value }
      // });
    } else if (response.data?.status && response.data?.status == '1') {
      getList()
    }
  });


  let completePar = {
    projectNo: projectNo.value,
    phaseId: 7//归档环节
  }
  await getStatus(completePar).then((response) => {
    if (response.data?.status && response.data?.status == '2') {//如果该环节已完成 跳转到下一个环节
      //判断收款是否已经收齐 收齐了跳已归档 没收齐跳待归档
      router.push({
        path: '/complete/projectComplete',
        query: { projectNo: projectNo.value }
      });
    } else if (response.data?.status && response.data?.status == '1') {
      router.push({
        path: '/complete/projectWait',
        query: { projectNo: projectNo.value }
      });
    } else {
      getList()
    }
  });


}

function getCurrPhase(projectNo) {
  let currPhase = {
    projectNo: projectNo,
    phaseId: 6//项目质保
  }
  getStatus(currPhase).then((response) => {
    console.log("当前阶段信息", response);
    if (response.data == null) {//没有查询到阶段信息  可以点击下一步 插入阶段信息
      //  currenrPhaseId.value = response.data.id
    } else {
      status.value = response.data.status
      currenrPhaseId.value = response.data.id
    }
  });
}






function getCurrPhaseConfig() {
  getDictionary(1).then(response => {//立项阶段 id写死 
    currentConfig.value = response.data;
  });
}

function getNextPer(projectNo) {
  let params = {
    projectNo: projectNo,
    id: 6//项目质保
  }
  getNextPermission(params).then(response => {//立项阶段 id写死
    console.log("项目前期 下一步权限", response);
    haveNext.value = response.data.permission

    addPersonPer.value = response.data.addPerson
    addFilePer.value = response.data.addFile
    addPayPer.value = response.data.addPay
    addImplementPer.value = response.data.addImplement
    addWarrantyPer.value = response.data.addWarranty
    addAccountingPer.value = response.data.addAccounting
    cw.value = response.data.cw
    allPer.value = response.data.admin

    isAdmin.value = response.data.admin

  });
}


initData()
onMounted(async () => {

  reset();

  let paramsW = {
    projectNo: projectNo.value
  }

  await getWarrantyMoney(paramsW).then((response) => {
    console.log("质保金", response);
    warrantyMoney.value = response.data?.totalWarranty
    receivedWarranty.value = response.data?.receivedWarranty
  });

  await saleDetails(projectNo.value).then((response) => {
    form.value = response.data;
    open.value = true;
    contractAmount.value = response.data.contractAmount
    settlementAmount.value = response.data.settlementAmount
    console.log("123213213213", settlementAmount.value);
    company.value = response.data.customerName

    completeDate.value = response.data.completeDate
  });
  await getListParticipan(projectNo.value)

});




loadUserColumnConfig()


// 所有可用列配置（可从接口获取）
const allColumns = [
  { label: "项目名称", prop: "projectName", visible: true },
  { label: "发起人", prop: "createUserName", visible: true },
  { label: "合同金额", prop: "contractAmount", visible: true },
  { label: "结算金额", prop: "settlementAmount", visible: true },
  { label: "质保金", prop: "warranty", visible: true },
  { label: "立项日期", prop: "approvalDate", visible: true },
  { label: "上次更新时间", prop: "updateTime", visible: true },
  { label: "质保起始日期", prop: "warrantyStartDate", visible: true },
  { label: "客户名称", prop: "customerName", visible: true },
  { label: "管家婆项目", prop: "housekeeperName", visible: true },
  { label: "保到期日期", prop: "warrantyEndDate", visible: true },
  { label: "阶段确认人", prop: "joinPeople", visible: true },
  { label: "当前操作人", prop: "currentPeople", visible: true },
]

// 用户当前选择的列 props（由 el-checkbox-group 控制）
const selectedProps = ref([])

// 当前可见列列表（根据 selectedProps 排序后的结果）
const visibleColumns = computed(() => {
  return selectedProps.value
    .map(prop => allColumns.find(col => col.prop === prop))
    .filter(Boolean)
})



// 当前可见列（根据用户选择动态变化）
const selectedColumns = ref([...allColumns])


const saveColumnConfig = async () => {

  console.log('保存配置', selectedProps.value);


  // 调用保存到后端的接口
  await saveUserTableConfig({ configs: selectedProps.value, type: "warranty" })
  proxy.$modal.msgSuccess("保存配置成功");

}

const getWidth = (prop) => {
  switch (prop) {
    case 'projectName':
    case 'approvalDate':
    case 'updateTime':
    case 'acceptTime':
      return 200;
    case 'housekeeperName':
      return 300;
    default:
      return undefined;
  }
}

async function loadUserColumnConfig() {
  const res = await getUserTableConfig({ type: "warranty" })

  let defaultOrder = allColumns
    .filter(col => col.visible !== false) // 可以根据 visible 控制是否默认显示
    .map(col => col.prop)

  if (res.data && Array.isArray(res.data)) {
    // 使用用户保存的顺序（只保留合法的 prop）
    selectedProps.value = res.data.filter(prop =>
      allColumns.some(col => col.prop === prop)
    )
  } else {
    // 否则使用默认顺序
    selectedProps.value = defaultOrder
  }
}

import useUserStore from '@/store/modules/user'

const userStore = useUserStore()


</script>
